{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "d642eb54",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"refresh_token\":\"25.f4c1e2718a2e2e0c299ec60070a1687f.315360000.1967513756.282335-25863841\",\"expires_in\":2592000,\"session_key\":\"9mzdWW7YTHiDqfGe9BwaBStAA7Mx2lMevqM6x6n8x\\/sV8Qro72b8v7m9UGda6IDemmdsY+v\\/0SW1JPdBHxjJ7Jc0Irx\\/nQ==\",\"access_token\":\"24.b4d15d85f6db52da2b90e141ce94fdf1.2592000.1654745756.282335-25863841\",\"scope\":\"audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope brain_advanced_general_classify brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test\\u6743\\u9650 vis-classify_flower lpq_\\u5f00\\u653e cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_\\u5f00\\u653eScope vis-ocr_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 idl-video_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx\",\"session_secret\":\"cf579d616360ecb24866bfc8622a63d3\"}\n",
      "\n",
      "{'refresh_token': '25.f4c1e2718a2e2e0c299ec60070a1687f.315360000.1967513756.282335-25863841', 'expires_in': 2592000, 'session_key': '9mzdWW7YTHiDqfGe9BwaBStAA7Mx2lMevqM6x6n8x/sV8Qro72b8v7m9UGda6IDemmdsY+v/0SW1JPdBHxjJ7Jc0Irx/nQ==', 'access_token': '24.b4d15d85f6db52da2b90e141ce94fdf1.2592000.1654745756.282335-25863841', 'scope': 'audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope brain_advanced_general_classify brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx', 'session_secret': 'cf579d616360ecb24866bfc8622a63d3'}\n",
      "audio_voice_assistant_get\n",
      "SUCCESS WITH TOKEN: 24.b4d15d85f6db52da2b90e141ce94fdf1.2592000.1654745756.282335-25863841  EXPIRES IN SECONDS: 2592000\n",
      "Request time cost 0.423011\n",
      "{\"corpus_no\":\"7095946351200491243\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"北京科技馆。\"],\"sn\":\"386434738831652153756\"}\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "import sys\n",
    "import json\n",
    "import base64\n",
    "import time\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        # On most other platforms the best timer is time.time()\n",
    "        timer = time.time\n",
    "\n",
    "API_KEY = 's9IYDG0uWXFYaf7nB1GZzqba'\n",
    "SECRET_KEY = 'nmCfa0rYGU3sn5NiKfcoRj8BKGpNjfVn'\n",
    "\n",
    "# 需要识别的文件\n",
    "AUDIO_FILE = '16k.pcm'  # 只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "# 文件格式\n",
    "FORMAT = AUDIO_FILE[-3:]  # 文件后缀只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "\n",
    "CUID = '123456PYTHON'\n",
    "# 采样率\n",
    "RATE = 16000  # 固定值\n",
    "\n",
    "# 普通版\n",
    "\n",
    "DEV_PID = 1537  # 1537 表示识别普通话，使用输入法模型。根据文档填写PID，选择语言及识别模型\n",
    "ASR_URL = 'http://vop.baidu.com/server_api'\n",
    "SCOPE = 'audio_voice_assistant_get'  # 有此scope表示有asr能力，没有请在网页里勾选，非常旧的应用可能没有\n",
    "\n",
    "#测试自训练平台需要打开以下信息， 自训练平台模型上线后，您会看见 第二步：“”获取专属模型参数pid:8001，modelid:1234”，按照这个信息获取 dev_pid=8001，lm_id=1234\n",
    "# DEV_PID = 8001 ;   \n",
    "# LM_ID = 1234 ;\n",
    "\n",
    "# 极速版 打开注释的话请填写自己申请的appkey appSecret ，并在网页中开通极速版（开通后可能会收费）\n",
    "\n",
    "# DEV_PID = 80001\n",
    "# ASR_URL = 'http://vop.baidu.com/pro_api'\n",
    "# SCOPE = 'brain_enhanced_asr'  # 有此scope表示有极速版能力，没有请在网页里开通极速版\n",
    "\n",
    "# 忽略scope检查，非常旧的应用可能没有\n",
    "# SCOPE = False\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://aip.baidubce.com/oauth/2.0/token'\n",
    "\n",
    "\n",
    "def fetch_token():\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode( 'utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str =  result_str.decode()\n",
    "\n",
    "    print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "    print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        print(SCOPE)\n",
    "        if SCOPE and (not SCOPE in result['scope'].split(' ')):  # SCOPE = False 忽略检查\n",
    "            raise DemoError('scope is not correct')\n",
    "        print('SUCCESS WITH TOKEN: %s  EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    token = fetch_token()\n",
    "\n",
    "    speech_data = []\n",
    "    with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "        speech_data = speech_file.read()\n",
    "\n",
    "    length = len(speech_data)\n",
    "    if length == 0:\n",
    "        raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "    speech = base64.b64encode(speech_data)\n",
    "    if (IS_PY3):\n",
    "        speech = str(speech, 'utf-8')\n",
    "    params = {'dev_pid': DEV_PID,\n",
    "             #\"lm_id\" : LM_ID,    #测试自训练平台开启此项\n",
    "              'format': FORMAT,\n",
    "              'rate': RATE,\n",
    "              'token': token,\n",
    "              'cuid': CUID,\n",
    "              'channel': 1,\n",
    "              'speech': speech,\n",
    "              'len': length\n",
    "              }\n",
    "    post_data = json.dumps(params, sort_keys=False)\n",
    "    # print post_data\n",
    "    req = Request(ASR_URL, post_data.encode('utf-8'))\n",
    "    req.add_header('Content-Type', 'application/json')\n",
    "    try:\n",
    "        begin = timer()\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "        print (\"Request time cost %f\" % (timer() - begin))\n",
    "    except URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "\n",
    "    if (IS_PY3):\n",
    "        result_str = str(result_str, 'utf-8')\n",
    "    print(result_str)\n",
    "    with open(\"result.txt\",\"w\") as of:\n",
    "        of.write(result_str)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fee887be",
   "metadata": {},
   "source": [
    "## 知识概念\n",
    "> 1.一切都是I/O：软工到产品的一般化知识                                 \n",
    "> 2.语音识别:speech recognition                                 \n",
    "> 3.语音唤醒                                                \n",
    "> 4.自动语音识别:Automatic Speech Recognition, 简称 ASR                                             \n",
    "其目标是以电脑自动将人类的语音内容转换为相应的文字。与说话人识别及说话人确认不同，后者尝试识别或确认发出语音的说话人而非其中所包含的词汇内容。\n",
    "                                                   \n",
    "> 5.语音合成:text to speech,简称 TTS\n",
    "将文字转化为语音的一种技术，类似于人类的嘴巴，通过不同的音色说出想表达的内容。 在语音合成技术中，主要分为 语言分析部分 和 声学系统部分 ，也称为 前端部分 和 后端部分， 语言分析部分主要是根据输入的文字信息进行分析，生成对应的语言学规格书，想好该怎么读；声学系统部分主要是根据语音分析部分提供的语音学规格书，生成对应的音频，实现发声的功能。                                            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "7c3d07fa",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.404ee4f70334b9bd819f3a2a510d7d37.315360000.1969283235.282335-25863841', 'expires_in': 2592000, 'session_key': '9mzdA5rjJkgPm+egByOw2n1h/NoEzkZFMI0aiqYj9fOCUMkX3c+zs75lBvyjDtnYmB+/1eTatLK3VNBd5/pLX2hwqlLb+A==', 'access_token': '24.807f3c6d11304f30b3b06128ff71859f.2592000.1656515235.282335-25863841', 'scope': 'audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope brain_advanced_general_classify brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx', 'session_secret': '6ea3bba2c27f8577d2a616ec6d416401'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?'\n",
    "payload = {\n",
    "    'grant_type':'client_credentials',\n",
    "    'client_id':'s9IYDG0uWXFYaf7nB1GZzqba',\n",
    "    'client_secret':'nmCfa0rYGU3sn5NiKfcoRj8BKGpNjfVn'\n",
    "}\n",
    "response = requests.get(host,params=payload)\n",
    "print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "67b091fd",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.807f3c6d11304f30b3b06128ff71859f.2592000.1656515235.282335-25863841'"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "token = response.json()['access_token']\n",
    "token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "16659fbe",
   "metadata": {},
   "outputs": [],
   "source": [
    "qa = {\n",
    "    \"你好呀\":\"你也好啊，看起来心情不错呀！\",\n",
    "    \"你叫什么\":\"我是小度\",\n",
    "    \"设置闹钟\":\"你想设置几点的闹钟呢？现在晚上12点了，早点休息呀！\"\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "49370989",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'你也好啊，看起来心情不错呀！'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "qa.get(\"你好呀\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "91fc5f81",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'我是小度'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "qa.get(\"你叫什么\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "0ce4bfc1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting pipwin\n",
      "  Downloading pipwin-0.5.2.tar.gz (7.9 kB)\n",
      "Collecting docopt\n",
      "  Downloading docopt-0.6.2.tar.gz (25 kB)\n",
      "Requirement already satisfied: requests in d:\\anaconda3\\lib\\site-packages (from pipwin) (2.25.1)\n",
      "Collecting pyprind\n",
      "  Downloading PyPrind-2.11.3-py2.py3-none-any.whl (8.4 kB)\n",
      "Requirement already satisfied: six in d:\\anaconda3\\lib\\site-packages (from pipwin) (1.15.0)\n",
      "Requirement already satisfied: beautifulsoup4>=4.9.0 in d:\\anaconda3\\lib\\site-packages (from pipwin) (4.9.3)\n",
      "Collecting js2py\n",
      "  Downloading Js2Py-0.71-py3-none-any.whl (1.0 MB)\n",
      "Requirement already satisfied: packaging in d:\\anaconda3\\lib\\site-packages (from pipwin) (20.9)\n",
      "Collecting pySmartDL>=1.3.1\n",
      "  Downloading pySmartDL-1.3.4-py3-none-any.whl (20 kB)\n",
      "Requirement already satisfied: soupsieve>1.2 in d:\\anaconda3\\lib\\site-packages (from beautifulsoup4>=4.9.0->pipwin) (2.2.1)\n",
      "Collecting pyjsparser>=2.5.1\n",
      "  Downloading pyjsparser-2.7.1.tar.gz (24 kB)\n",
      "Collecting tzlocal>=1.2\n",
      "  Downloading tzlocal-4.2-py3-none-any.whl (19 kB)\n",
      "Collecting tzdata\n",
      "  Downloading tzdata-2022.1-py2.py3-none-any.whl (339 kB)\n",
      "Collecting pytz-deprecation-shim\n",
      "  Downloading pytz_deprecation_shim-0.1.0.post0-py2.py3-none-any.whl (15 kB)\n",
      "Collecting backports.zoneinfo\n",
      "  Downloading backports.zoneinfo-0.2.1-cp38-cp38-win_amd64.whl (38 kB)\n",
      "Requirement already satisfied: pyparsing>=2.0.2 in d:\\anaconda3\\lib\\site-packages (from packaging->pipwin) (2.4.7)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in d:\\anaconda3\\lib\\site-packages (from requests->pipwin) (1.26.4)\n",
      "Requirement already satisfied: chardet<5,>=3.0.2 in d:\\anaconda3\\lib\\site-packages (from requests->pipwin) (4.0.0)\n",
      "Requirement already satisfied: idna<3,>=2.5 in d:\\anaconda3\\lib\\site-packages (from requests->pipwin) (2.10)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in d:\\anaconda3\\lib\\site-packages (from requests->pipwin) (2020.12.5)\n",
      "Building wheels for collected packages: pipwin, docopt, pyjsparser\n",
      "  Building wheel for pipwin (setup.py): started\n",
      "  Building wheel for pipwin (setup.py): finished with status 'done'\n",
      "  Created wheel for pipwin: filename=pipwin-0.5.2-py2.py3-none-any.whl size=8776 sha256=16d87bd9453399061205095d68b210aa332cf8e6a733200e4f7d495967031235\n",
      "  Stored in directory: c:\\users\\23897\\appdata\\local\\pip\\cache\\wheels\\f4\\a8\\76\\372879a40d2d4dd7de23efd867ed37112687429b8d0dda4545\n",
      "  Building wheel for docopt (setup.py): started\n",
      "  Building wheel for docopt (setup.py): finished with status 'done'\n",
      "  Created wheel for docopt: filename=docopt-0.6.2-py2.py3-none-any.whl size=13705 sha256=f1048b5931b18905395fec62029b283663ecda79b0f559ffa7d05f2fee74da0b\n",
      "  Stored in directory: c:\\users\\23897\\appdata\\local\\pip\\cache\\wheels\\56\\ea\\58\\ead137b087d9e326852a851351d1debf4ada529b6ac0ec4e8c\n",
      "  Building wheel for pyjsparser (setup.py): started\n",
      "  Building wheel for pyjsparser (setup.py): finished with status 'done'\n",
      "  Created wheel for pyjsparser: filename=pyjsparser-2.7.1-py3-none-any.whl size=25998 sha256=9984c3b55afc3b4f4594cbd4a2b0c44644074f06483e592616f1637b696e2314\n",
      "  Stored in directory: c:\\users\\23897\\appdata\\local\\pip\\cache\\wheels\\d5\\88\\34\\ccb5bb40eb3178a134eb293e6c363928c5bcfba0b91031db76\n",
      "Successfully built pipwin docopt pyjsparser\n",
      "Installing collected packages: tzdata, backports.zoneinfo, pytz-deprecation-shim, tzlocal, pyjsparser, pySmartDL, pyprind, js2py, docopt, pipwin\n",
      "Successfully installed backports.zoneinfo-0.2.1 docopt-0.6.2 js2py-0.71 pipwin-0.5.2 pySmartDL-1.3.4 pyjsparser-2.7.1 pyprind-2.11.3 pytz-deprecation-shim-0.1.0.post0 tzdata-2022.1 tzlocal-4.2\n"
     ]
    }
   ],
   "source": [
    "!pip install pipwin"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "26205690",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Building cache. Hang on . . .\n",
      "Done\n",
      "Package `pyaudio` found in cache\n",
      "Downloading package . . .\n",
      "https://download.lfd.uci.edu/pythonlibs/a4hvik9m/PyAudio-0.2.11-cp38-cp38-win_amd64.whl\n",
      "PyAudio-0.2.11-cp38-cp38-win_amd64.whl\n",
      "[*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 8 kB / 111 kB @ 7 kB/s [#-----------------] [7.2%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 8 kB / 111 kB @ 6 kB/s [#-----------------] [7.2%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 40 kB / 111 kB @ 29 kB/s [######------------] [36.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 40 kB / 111 kB @ 27 kB/s [######------------] [36.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 40 kB / 111 kB @ 25 kB/s [######------------] [36.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 40 kB / 111 kB @ 24 kB/s [######------------] [36.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 40 kB / 111 kB @ 22 kB/s [######------------] [36.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b Processing c:\\users\\23897\\pipwin\\pyaudio-0.2.11-cp38-cp38-win_amd64.whl\n",
      "Installing collected packages: PyAudio\n",
      "Successfully installed PyAudio-0.2.11\n",
      "[*] 111 kB / 111 kB @ 22 kB/s [##################] [100%, 0s left]    \n"
     ]
    }
   ],
   "source": [
    "!pipwin install PyAudio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "4a97cc80",
   "metadata": {},
   "outputs": [],
   "source": [
    "import speech_recognition\n",
    "r = speech_recognition.Recognizer()\n",
    "\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "6e8feb9c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你也好啊，看起来心情不错呀！\n"
     ]
    }
   ],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "import sys\n",
    "import json\n",
    "import time\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        # On most other platforms the best timer is time.time()\n",
    "        timer = time.time\n",
    "\n",
    "API_KEY = 's9IYDG0uWXFYaf7nB1GZzqba'\n",
    "SECRET_KEY = 'nmCfa0rYGU3sn5NiKfcoRj8BKGpNjfVn'\n",
    "\n",
    "# 需要识别的文件\n",
    "AUDIO_FILE = '1.wav'  # 只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "# 文件格式\n",
    "FORMAT = AUDIO_FILE[-3:];  # 文件后缀只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "\n",
    "CUID = '123456PYTHON';\n",
    "# 采样率\n",
    "RATE = 16000;  # 固定值\n",
    "\n",
    "# 普通版\n",
    "\n",
    "DEV_PID = 1537;  # 1537 表示识别普通话，使用输入法模型。根据文档填写PID，选择语言及识别模型\n",
    "ASR_URL = 'http://vop.baidu.com/server_api'\n",
    "SCOPE = 'audio_voice_assistant_get'  # 有此scope表示有asr能力，没有请在网页里勾选，非常旧的应用可能没有\n",
    "\n",
    "#测试自训练平台需要打开以下信息， 自训练平台模型上线后，您会看见 第二步：“”获取专属模型参数pid:8001，modelid:1234”，按照这个信息获取 dev_pid=8001，lm_id=1234\n",
    "# DEV_PID = 8001 ;   \n",
    "# LM_ID = 1234 ;\n",
    "\n",
    "# 极速版 打开注释的话请填写自己申请的appkey appSecret ，并在网页中开通极速版（开通后可能会收费）\n",
    "\n",
    "#DEV_PID = 80001\n",
    "#ASR_URL = 'http://vop.baidu.com/pro_api'\n",
    "#SCOPE = 'brain_enhanced_asr'  # 有此scope表示有asr能力，没有请在网页里开通极速版\n",
    "\n",
    "# 忽略scope检查，非常旧的应用可能没有\n",
    "# SCOPE = False\n",
    "\n",
    "\n",
    "# 极速版\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://aip.baidubce.com/oauth/2.0/token'\n",
    "\n",
    "\n",
    "def fetch_token():\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "\n",
    " #   print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "   # print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if SCOPE and (not SCOPE in result['scope'].split(' ')):  # SCOPE = False 忽略检查\n",
    "            raise DemoError('scope is not correct')\n",
    "      #  print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    token = fetch_token()\n",
    "\n",
    "    \"\"\"\n",
    "    httpHandler = urllib2.HTTPHandler(debuglevel=1)\n",
    "    opener = urllib2.build_opener(httpHandler)\n",
    "    urllib2.install_opener(opener)\n",
    "    \"\"\"\n",
    "\n",
    "    speech_data = []\n",
    "    with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "        speech_data = speech_file.read()\n",
    "    length = len(speech_data)\n",
    "    if length == 0:\n",
    "        raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "\n",
    "    params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID}\n",
    "    #测试自训练平台需要打开以下信息\n",
    "    #params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID, 'lm_id' : LM_ID}\n",
    "    params_query = urlencode(params);\n",
    "\n",
    "    headers = {\n",
    "        'Content-Type': 'audio/' + FORMAT + '; rate=' + str(RATE),\n",
    "        'Content-Length': length\n",
    "    }\n",
    "\n",
    "    url = ASR_URL + \"?\" + params_query\n",
    "  #  print(\"url is\", url);\n",
    "  #  print(\"header is\", headers)\n",
    "    # print post_data\n",
    "    req = Request(ASR_URL + \"?\" + params_query, speech_data, headers)\n",
    "    try:\n",
    "        begin = timer()\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "  #      print(\"Request time cost %f\" % (timer() - begin))\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "\n",
    "    if (IS_PY3):\n",
    "        result_str = str(result_str, 'utf-8')  # result_str 已经是字符串（字典）\n",
    "        # print(eval(result_str)[\"result\"][0][:-1])\n",
    "    print(qa.get(eval(result_str)[\"result\"][0][:-1]))   # eval（）将str-->dict\n",
    "    with open(\"result.txt\", \"w\") as of:\n",
    "        of.write(result_str)\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "e06e5154",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'corpus_no': '7103551522191301711',\n",
       " 'err_msg': 'success.',\n",
       " 'err_no': 0,\n",
       " 'result': ['你好呀。'],\n",
       " 'sn': '53537145861653924473'}"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# str 转换成 dict\n",
    "result_str = eval(result_str)\n",
    "result_str"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "14655ec2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'你好呀'"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 取出文本\n",
    "txt = result_str[\"result\"][0][:-1]\n",
    "txt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b440716",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
